#!/bin/bash

cpDestOpts=--preserve=timestamps

if [[ "$PhotivoRepoPath"  == "" ]];            then printf "PhotivoRepoPath not set!\n"    ; exit 1 ; fi
if [[ "$PhotivoBuildPath" == "" ]];            then printf "PhotivoBuildPath not set!\n"   ; exit 1 ; fi
if [[ "$GccArch"          == "" ]];            then printf "GccArch not set!\n"            ; exit 1 ; fi
if [[ ($GccArch != 64) && ($GccArch != 32) ]]; then printf "Wrong GccArch (${GccArch})!\n" ; exit 1 ; fi

Result () {
    if [[ $1 == 0 ]]; then
        printf "\e[0;32mUpdating DLLs succeeded!\e[00m\n"
        exit 0
    else
        printf "\e[1;31mUpdating DLLs failed!\e[00m\n"
        exit 1
    fi
}

#=============================================================================

if [[ "$1" != "" ]]; then
    TheBindir="$1"
else
    if [ ! -d "$PhotivoBuildPath" ]; then
        echo "Path to build folder \"$PhotivoBuildPath\" not found."
        exit 1
    fi
    TheBindir="$PhotivoBuildPath"
fi


echo "Updating all DLLs in $TheBindir ... "

if [ ! -d "$TheBindir" ]; then
    mkdir -p "$TheBindir"
else
    rm -f "$TheBindir/*.dll"
fi


cd /mingw/qt/bin && \
cp QtCore4.dll \
   QtGui4.dll \
   QtNetwork4.dll \
   $TheBindir $cpDestOpts && \
cd /my/bin && \
cp libexiv2.dll \
   libexpat-1.dll \
   libfftw3-3.dll \
   libglib-2.0-0.dll \
   libGraphicsMagick-3.dll \
   libGraphicsMagick++-3.dll \
   libGraphicsMagickWand-2.dll \
   libiconv-2.dll \
   libjpeg-8.dll \
   liblcms2-2.dll \
   liblensfun.dll \
   liblqr-1-0.dll \
   libpng15-15.dll \
   libtiff-5.dll \
   zlib1.dll \
   $TheBindir $cpDestOpts
Status=$?

if [[ $Status == 0 ]]; then
    if [[ "$GccArch" == "64" ]]; then
        cp libintl-8.dll \
           $TheBindir $cpDestOpts && \
        cd /mingw/bin && \
        cp libgcc_s_sjlj_64-1.dll \
           libgomp_64-1.dll \
           libstdc++_64-6.dll \
           pthreadGC2_64.dll \
           $TheBindir $cpDestOpts

    elif [[ "$GccArch" == "32" ]]; then
        cp intl.dll \
           $TheBindir $cpDestOpts && \
        cd /mingw/bin && \
        cp libgcc_s_sjlj-1.dll \
           libgomp-1.dll \
           libstdc++-6.dll \
           pthreadGC2.dll \
           $TheBindir $cpDestOpts
    fi
    
    Status=$?
fi

if [[ $Status == 0 ]]; then
    printf "\e[0;32mUpdating DLLs succeeded!\e[00m\n"
    exit 0
else
    printf "\e[1;31mUpdating DLLs failed!\e[00m\n"
    exit $Status
fi